<template>
  <Form class="xtx-form" :validation-schema="mySchema" autocomplete="off" v-slot='{errors}' ref="formCom" >
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" class="input" type="text" placeholder="绑定的手机号" name="mobile" v-model="form.mobile" />
      </div>
      <div v-if="errors.mobile" class="error">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" class="input" type="text" placeholder="短信验证码" name="code" v-model="form.code" />
        <span class="code" @click="send">{{time===0?'发送验证码':`${time}秒重新发送`}}</span>
      </div>
      <div v-if="errors.code" class="error">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { onUnmounted, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useIntervalFn } from '@vueuse/shared'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const store = useStore()
    const router = useRouter()
    const formCom = ref(null)
    const nickname = ref('null') // 昵称
    const avatar = ref('null') // 头像
    if (QC.Login.check()) { // 已登录
      QC.api('get_user_info').success(res => {
        nickname.value = res.data.nickname
        avatar.value = res.data.figureurl_1
      })
    }
    const form = ref({
      mobile: null,
      code: null
    })
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }

    // 设置计时器 停止 开始
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0)pause()
    }, 1000, false) // 是否立即开启
    onUnmounted(() => {
      pause()
    })
    // 发送验证码
    async function send () {
      const valid = mySchema.mobile(form.value.mobile) // 校验手机号
      if (valid === true) {
        if (time.value !== 0) return
        try {
          await userQQBindCode(form.value.mobile)
          Message({ type: 'success', text: '发送成功' })
          time.value = 60
          resume() // 开启定时
        } catch (e) {
          Message({ type: 'error', text: e.response.data.message || '发送失败' })
        }
      } else {
        formCom.value.setFieldError('mobile', valid) // 显示错误信息
      }
    }
    // 立即绑定
    async function submit () {
      // 表单校验 valid===true通过
      const valid = await formCom.value.validate()
      if (valid) {
        try {
          const data = await userQQBindLogin({
            unionId: props.unionId,
            ...form.value
          })
          // 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 合并购物车
          store.dispatch('cart/mergeCart').then(() => {
            // 读取记录的原地址信息，以在完成登录后回到原先页面
            router.push(store.state.user.redirectUrl)
            Message({ type: 'success', text: '绑定成功' })
          })
        } catch (e) {
          if (e.response.data)Message({ type: 'error', text: e.response.data.message || '绑定失败' })
        }
      }
    }

    return { nickname, avatar, form, mySchema, send, formCom, time, submit }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
